package me.leiusual.sharing.widget

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import androidx.core.content.res.ResourcesCompat
import kotlinx.android.synthetic.main.layout_amount.view.*
import me.leiusual.sharing.R

/**
 * author: leiusual
 * create on: 2019-07-27
 * description:
 */
class AmountView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr), View.OnClickListener {

  var minAmount = 1 // 最小值
  var maxAmount = 1 // 库存

  var listener: Listener? = null

  init {
    View.inflate(context, R.layout.layout_amount, this)
    dividerDrawable = ResourcesCompat.getDrawable(context.resources, R.drawable.all_divider, null)
    showDividers = SHOW_DIVIDER_MIDDLE
    background = ResourcesCompat.getDrawable(context.resources, R.drawable.amount_view_background, null)

    btnDecrease.setOnClickListener(this)
    btnIncrease.setOnClickListener(this)
  }

  override fun onClick(v: View?) {
    var amount = etAmount.text.toString().toIntOrNull() ?: 1
    when (v?.id) {
      R.id.btnDecrease -> {
        if (amount > minAmount) {
          amount--
          listener?.onAmountClicked(amount)
        }
      }
      R.id.btnIncrease -> {
        if (amount < maxAmount) {
          amount++
          listener?.onAmountClicked(amount)
        }
      }
    }
    etAmount.clearFocus()
    etAmount.setText(amount.toString())
  }

  interface Listener {

    fun onAmountClicked(amount: Int)
  }
}